package com.helsinki.controller;

import com.github.pagehelper.PageInfo;
import com.helsinki.pojo.Permission;
import com.helsinki.pojo.Product;
import com.helsinki.pojo.Role;
import com.helsinki.service.PermissionService;
import com.helsinki.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("list")
    @ResponseBody
    public PageInfo<Role> list(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {
        return roleService.queryAll(pageNum, pageSize);
    }

    @RequestMapping("roleList")
    @ResponseBody
    public List<Role> roleList(){
        return roleService.findAll();
    }

    @RequestMapping("findById")
    @ResponseBody
    public Role findById(@RequestParam String id) {
        return roleService.queryById(id);
    }

    @RequestMapping("insert")
    public String save(@RequestBody Role role) throws Exception {
        String str = "";
        try {
            roleService.addRole(role);
            str = "添加成功,";
        } catch (Exception e) {
            e.printStackTrace();
            str = "添加失败！请重新添加！！！";
        }
        return "redirect:/pages/role-list.html";
    }

    @RequestMapping("update")
    public String update(@RequestBody Role role) {
        roleService.updateRole(role);
        return "redirect:/pages/role-list.html";
    }

    @RequestMapping("findPermissionById")
    @ResponseBody
    public Role permissionList(@RequestParam String id) {
        Role role = roleService.queryById(id);
        List<String> select = new ArrayList<>();
        for (Permission per : role.getPermissions()) {
            select.add(per.getId());
        }
        role.setSelect(select);
        return role;
    }

    @RequestMapping("updateRolePermission")
    @ResponseBody
    public String updateRolePermission(@RequestBody Role role){
        roleService.updateRolePermission(role);
        return null;
    }

    //删除角色
    @RequestMapping("/deleteRole")
    @ResponseBody
    public Boolean delete(@RequestBody String id){
        id = id.substring(0,id.length()-1);
        System.out.println(id);
        return roleService.deleteById(id);
    }

}
